package com.ocn.li.scmdy.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;


/**
 * Created by 旧的jwttoken
 */
@Component
public class FjqJwtUtil
{

    private static String base64Secret = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=";

    private long expire;

    public static Claims parseJWT(String jsonWebToken, String base64Security){
        try
        {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        }
        catch(Exception ex)
        {
            return null;
        }
    }

    /**
     *
     * 创建JWT秘钥
     *
     * @param accountName
     * @param audience
     * @param issuer
     * @return
     */
    public static String createJWT(String accountName, String audience, String issuer, String accountId,String DataAreaCode)
    {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis =System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
       byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=");
        //byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);

        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("type", "JWT")
                .claim("accountName", accountName)
                .claim("accountId", accountId)
                .claim("dataAreaCode", DataAreaCode)
                .setIssuer(issuer)
                .setAudience(audience)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        String tokenKeepTime = "720";
        if(StringUtils.isNotBlank(tokenKeepTime))
        {

            long expMillis = nowMillis + Integer.parseInt(tokenKeepTime)*60*1000;
//            long expMillis = nowMillis + 30*60*1000;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        //生成JWT
        return builder.compact();
    }

    public static String getBase64Secret() {
        return base64Secret;
    }

    public static void setBase64Secret(String base64Secret) {
        FjqJwtUtil.base64Secret = base64Secret;
    }

    public static void main(String args[]) {
        String tokenStr = FjqJwtUtil.createJWT("fjq","fjq","1","","");
        System.out.println(tokenStr);
        Claims claims = FjqJwtUtil.parseJWT(tokenStr, base64Secret);
        System.out.println(claims.toString());


        System.out.println(new Date(1486279081165L));
        System.out.println(new Date((1486280902L*1000L)));

    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(base64Secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 验证token是否过期
     * @param expiration
     * @return
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}
